<?php
namespace Home\Logic\OrderLogic;

use My\Model\WechatUserModel;
use My\Model\UserRole;
use Home\Logic\OrderLogic\AgentPackageOrder\PackageOrderReward;
use My\Model\DistributionShopPackageModel;
use My\Model\OrderModel;
/**
 * 代理升级订单业务类
 * @author song
 */
class AgentPackageOrder extends Order {
	
	/**
	 * 订单扩展属性
	 * @var array
	 */
	protected $orderExtendFields = array('agent_recommend_tree', 'agent_layer_tree', 'settle_status', 'reward_uids', 'reward_bonus', 'reward_uids_recommend', 'reward_bonus_recommend', 'user_type');
	
	/**
	 * 订单商品扩展属性
	 * @var array
	 */
	protected $orderGoodsExtendFields = array('reward_uids', 'reward_percent', 'reward_bonus', 'reward_uids_recommend', 'reward_percent_recommend',  'reward_bonus_recommend');
	
	/**
	 * 订单数据库中一条订单的关联数据
	 */
	public function getOne( $orderId ) {
		$condition = array(
				"orders.id" => $orderId,
		);
		$order = M ( "Order orders" )->join("__ORDER_PACKAGE_EXTEND__ extend on orders.id=extend.order_id", "LEFT")
									->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
									->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
									->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
									->field ( "orders.*,province.name as provinceName, city.name as cityName, area.name as areaName,
											   extend.agent_recommend_tree,extend.agent_layer_tree,extend.settle_status,extend.reward_uids,extend.reward_bonus,extend.reward_uids_recommend,extend.reward_bonus_recommend,extend.user_type" )
									->where ( $condition )
									->find ();
		return $order;
	}
	
	/**
	 * 获得订单列表
	 * @param 条件 $condition
	 * @return array
	 */
	public function getList( $condition ) {
	    $m = M ( "Order orders" );
	    $orderLists = $m->join("__ORDER_PACKAGE_EXTEND__ extend on orders.id=extend.order_id", "LEFT")
						->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
						->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
						->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
						->field ( "orders.*,province.name as provinceName, city.name as cityName, area.name as areaName,
								   extend.agent_recommend_tree,extend.agent_layer_tree,extend.settle_status,extend.reward_uids,extend.reward_bonus,extend.reward_uids_recommend,extend.reward_bonus_recommend,extend.user_type" )
						->where ( $condition )
                	    ->select ();
	    return $orderLists;
	}
	
	/**
	 * 获得订单商品列表关联数据
	 * @param unknown $orderId
	 */
	protected function getOrderGoodsList( $orderId ) {
		return M("OrderGoods a")->join('__ORDER_PACKAGE_ITEMS__ b on a.id=b.order_goods_id', 'LEFT')->where ( "a.order_id=%d", $orderId )
								->field("a.*,b.reward_uids,b.reward_percent,b.reward_bonus,b.reward_uids_recommend,b.reward_percent_recommend,b.reward_bonus_recommend")->select ();
	}
	
	/**
	 * 获得一个购买时的商品
	 * @param unknown $goodsId
	 * @return mixed
	 * array(
	 * 	 'take_price' => '0.00', // 拍下价格
	 * 	 // ... ...
	 * )
	 */
	protected function getBuyGoodsOne( $goodsId ) {
	    $m = M("DistributionShopPackage");
	    $goodsOne = $m->where('cid=%d and id=%d', $this->cid, $goodsId)->find();
	    if ( $goodsOne ) {
	        /* 配送配置 */
	        if ( $goodsOne['shipping_config'] ) {
	            $goodsOne['shipping_config'] = unserialize($goodsOne['shipping_config']);
	        }
	        /* 套餐扩展配置 */
	        if ( $goodsOne['config'] ) {
	            $goodsOne['config'] = unserialize($goodsOne['config']);
	        }
	        $goodsOne['images'] = array($goodsOne['image']);
	        $goodsOne['attrs_cfg'] = $attrs_cfg = ($goodsOne['attrs_cfg'] ? unserialize($goodsOne['attrs_cfg']) : array());
	        /* 拍下价格处理 */
	        $goodsOne['take_price'] =  $goodsOne['price'];
	    	$userRole = new UserRole();
	        if ( $userRole->type($this->user['type'])->is(WechatUserModel::USER_TYPE_AGENT) ) { // 是代理商
	            /* 获得代理商折扣价 */
	            $agent = M("Agent")->where("cid=%d and wechat_uid=%d", $this->cid, $this->uid)->find();
	            $agentLevel = $agent['level']*1; // 代理等级
	            if ( $agent and $goodsOne['config'] ) {
	                $pConfig = array();
	                if ( $goodsOne['config']['base'] ) {
	                    $pConfig = $goodsOne['config']['base'];
	                }
	                if ( $goodsOne['config'][$goodsOne['type']] ) {
	                    $pConfig = array_merge($pConfig, $goodsOne['config'][$goodsOne['type']] );
	                }
	                if ( isset($pConfig['discount']) ) { // 配置了折扣价
	                    $discount = $pConfig['discount'][$agentLevel]*1; // 所享折扣
	                    if ( $discount ) {
	                        $goodsOne['take_price'] = sprintf("%.2f", $goodsOne['price']*$discount/100);
	                    }
	                }
	            }
	        }
	    }
	    return $goodsOne;
	}
	
	/**
	 * saveing 时绑定商品扩展信息
	 * @param unknown $goods
	 */
	protected function bindGoodsExtends( &$order ) {
	    $userRole = new UserRole();
	    $agentRecommendTree = ""; // 推荐树
	    $agentLayerTree = ""; // 层级树
	    $snapGoods = $order['snapGoods'];
	    /* 定义要重设的订单属性 */
	    $rewriteOrder = array();
	    $userRole->type($this->user['type']);
	    if ( $userRole->is(WechatUserModel::USER_TYPE_AGENT) ) { // 买家为代理商
	        // 获得层级树
	        $buyer = $agent = M("Agent")->where("cid=%d and wechat_uid=%d", $this->cid, $this->uid )->find(); // 代理商
	        $agentRecommendTree = $buyer['tree'];
	        $level = $buyer['level']*1; // 代理商等级
	        $agentLayerTree = $buyer['id']; // 层级树
	        while ( $agent['parent_id']*1 != 0 ) {
	            $agent = M("Agent")->where("id=%d", $agent['parent_id'] )->find(); // 上级代理商
	            $spaceLevel = $level - $agent['level'] - 1;
	            for ( $i=0; $i<$spaceLevel; $i++ ) {
	                $agentLayerTree.=",0";
	            }
	            $agentLayerTree.= ",{$agent['id']}";
	            $level = $agent['level'];
	        }
	        if ( $level ) {
	            $spaceLevel = $level;
	            for ( $i=0; $i<$spaceLevel; $i++ ) {
	                $agentLayerTree.=",0";
	            }
	        }
	        // 计算分返佣
	        $orderReward = array(); // 订单返佣
	        $orderRewardRecommend = array(); // 订单培养返佣
	        foreach ( $order['items'] as $goodsId => &$goods ) {
	            $goodsOne = $snapGoods[$goodsId];
	            $packageType = $goodsOne['type'];
	            /* 基础配置 */
	            $packageConfig = $goodsOne['config']['base'] ? $goodsOne['config']['base'] : array() ;
	            /* 扩展配置  */
	            $extendsPackageConfig = $goodsOne['config'][$packageType];
	            if ( $extendsPackageConfig ) {
	                $packageConfig = array_merge($packageConfig, $extendsPackageConfig);
	            }
	            /* 计算单件商品分返佣 */
	            if ( $packageConfig and isset($packageConfig['discount'] ) ) { // 代理购买商品折扣
	                // 商品返佣比例计算
	                $discount = $packageConfig['discount'];
	                $rewardPercent = PackageOrderReward::calcRewardPercentByDiscount($discount, $buyer['level']*1-1); // 按购买者计算的返佣比例   厂家比例:一级比例:二级比例
	            }
	            if ( $rewardPercent ) {
	                foreach ( $goods['items'] as $attrGoodsId => &$attrGoods ) {
	                    $goodsSourcePrice = $goodsOne['price']; // 商品原价格
	                    $goodsNumber = $attrGoods['goods_number']; // 商品数量
	                    // 分佣原始金额(含厂家  厂家分佣:一级分佣:二级分佣) 
	                    $rewardBonus = array();
	                    foreach ( $rewardPercent as $v ) {
	                        $rewardBonus[] = sprintf('%.2f', ($goodsSourcePrice*$goodsNumber)*($v/100));
	                    }
	                    // 分佣代理(含厂家  s:一级uid:二级uid)
	                    $agentLayerTreeArray = explode(',', $agentLayerTree);
	                    $rewardUids = array();
	                    for ( $i=count($agentLayerTreeArray)-1; $i>=0; $i-- ) {
	                        $rewardUids[] = $agentLayerTreeArray[$i];
	                    }
	                    $rewardUids and array_unshift($rewardUids, 's');
	                    // 裁剪
	                    $rewardUids = array_slice($rewardUids, 0, count($rewardPercent));
	                    $rewardBonus = array_slice($rewardBonus, 0, count($rewardUids));
	                    // 空级代理佣金并入厂家
                        for ( $i = 0; $i < count($rewardUids); $i++ ) {
                            if (  $rewardUids[$i] !== 's' and $rewardUids[$i]*1 === 0 ) { // 非厂家空级代理
                                $rewardPercent[0] += $rewardPercent[$i]; // 空级代理分佣比例并入厂商
                                $rewardBonus[0] += $rewardBonus[$i]; // 空级代理分佣金额并入厂商
                                $rewardPercent[$i] = 0;
                                $rewardUids[$i] = 0;
                                $rewardBonus[$i] = 0;
                            }
                        }
                        // 绑定订单商品分佣字段
                        $attrGoods['reward_percent'] = join(':', $rewardPercent);
                        $attrGoods['reward_uids'] = join(',', $rewardUids);
                        $attrGoods['reward_bonus'] = join(',', $rewardBonus);
                        // 汇总订单返佣
                        $combineReward = array_combine($rewardUids, $rewardBonus);
                        foreach ( $combineReward as $uid => $v ) {
                            if ( $uid*1 === 0 ) continue;
                            $orderReward[$uid] += $v;
                        }              
	                }
	            }
	            /* 培养树分佣 */
	            if ( $packageConfig and isset($packageConfig['recommendBouns'] ) ) { // 代理购买商品折扣
	                // 商品返佣比例计算
	                $recommendBouns = $packageConfig['recommendBouns'];
	                $recommendPercent = $packageConfig['recommendPercent'];
	            }
	            $agentRecommendArray = explode(',', $agentRecommendTree);
	            array_shift($agentRecommendArray);
	            if ( $agentRecommendArray and $recommendBouns > 0 and !empty($recommendPercent)  ) {
	                $recommendPercentArray = explode(':', $recommendPercent);
	                foreach ( $goods['items'] as $attrGoodsId => &$attrGoods ) {
	                    $goodsNumber = $attrGoods['goods_number']; // 商品数量
	                    $sumRecommendBouns = $recommendBouns*$goodsNumber;
	                    // 分佣代理(培养分佣用户)
	                    $rewardUidsRecommend = array_slice($agentRecommendArray, 0, count($recommendPercentArray));
	                    $rewardPercentRecommend = array_slice($recommendPercentArray, 0, count($rewardUidsRecommend));
	                    // 分佣代理(培养分佣用户)
	                    $rewardBonusRecommend = array();
	                    foreach ( $rewardPercentRecommend as $v ) {
	                        $rewardBonusRecommend[] =  sprintf('%.2f', $sumRecommendBouns*$v/100);
	                    }
	                    // 绑定订单商品分佣字段
	                    $attrGoods['reward_percent_recommend'] = join(':', $rewardPercentRecommend);
	                    $attrGoods['reward_uids_recommend'] = join(',', $rewardUidsRecommend);
	                    $attrGoods['reward_bonus_recommend'] = join(',', $rewardBonusRecommend);
	                    // 汇总订单返佣
	                    $combineReward = array_combine($rewardUidsRecommend, $rewardBonusRecommend);
	                    foreach ( $combineReward as $uid => $v ) {
	                        $orderRewardRecommend[$uid] += $v;
	                    }
	                }
	            }
	        }
	        /* 重设订单属性 */
	        $rewriteOrder = array_merge($rewriteOrder, array(
	            'agent_recommend_tree' => $agentRecommendTree, // 代理推荐树
	            'agent_layer_tree' => $agentLayerTree, // 代理层次数
	        ));
	        // 订单分佣
	        if ( $orderReward ) {
	            $rewriteOrder['reward_uids'] = join(',', array_keys($orderReward));
	            $rewriteOrder['reward_bonus'] = join(',', array_values($orderReward));
	        } 
	        // 订单培养分佣
	        if( $orderRewardRecommend ) {
	            $rewriteOrder['reward_uids_recommend'] = join(',', array_keys($orderRewardRecommend));
	            $rewriteOrder['reward_bonus_recommend'] = join(',', array_values($orderRewardRecommend));
	        }
	    }
	    foreach ( $rewriteOrder as $k => $v ) {
	        $order[$k] = $v;
	    }
	}
	
	/**
	 * saveing 时绑定订单扩展与修改订单数据信息
	 * @param unknown $order
	 */
	public function bindExtends( &$order ) {
	    $wechatUser = M("WechatUser")->where("id=%d and cid=%d", $order['uid'], $order['cid'])->find();
	    /* 定义要重设的订单属性 */
	    $rewriteOrder = array();
	    $userRole = new UserRole();
	    if ( $userRole->type($wechatUser['type'])->is(WechatUserModel::USER_TYPE_AGENT) ) { // 已是代理从厂家购买
	        $rewriteOrder['agent_id'] = 0;
	    }
	    
	    $rewriteOrder['type'] = OrderModel::ORDER_TYPE_AGENT_PACKAGE;
	    /* 订单扩展信息 */
	    $orderExtends = array(
	        'settle_status' => 0,
	        'user_type' => $wechatUser['type'], // 用户类型
	        'reward_uids' => null,
	        'reward_bonus' => null,
	        'reward_uids_recommend' => null,
	        'reward_bonus_recommend' => null,
	    );
	    /* 应用订单属性 */
	    foreach ( $rewriteOrder as $k => $v ) {
	        $order[$k] = $v;
	    }
	    /* 应用订单扩展属性 */
	    foreach ( $orderExtends as $k => $v ) {
	        $order[$k] = $v;
	    }
	    $this->bindGoodsExtends( &$order );
	}
	
	/**
	 * 添加订单扩展信息
	 * @param $order 订单关联数组(含order_id)
	 * @param $goodsList 订单商品一维数组(含order_goods_id) $order
	 */
	protected function addExtends( $order, $goodsList ) {
	    $orderId = $order['order_id'];
	    $orderExtends = array(
            "order_id" => $orderId,
	        "settle_status" => $order['settle_status'],
	        'user_type' => $order['user_type'],
	        'reward_uids' => $order['reward_uids'],
	        'reward_bonus' => $order['reward_bonus'],
	        'reward_uids_recommend' => $order['reward_uids_recommend'],
	        'reward_bonus_recommend' => $order['reward_bonus_recommend'],
	        'agent_recommend_tree' => $order['agent_recommend_tree'],
	        'agent_layer_tree' => $order['agent_layer_tree'],
        );
        $result =  M("OrderPackageExtend")->add($orderExtends);
        if ( $result ) {
            $goodsExtends = array();
            foreach ( $order['items'] as $goodsId => $goods ) {
                $data = array(
                    'order_id' => $orderId,
                );
                foreach ( $goods['items'] as $v ) {
                    $data['order_goods_id'] = $v['order_goods_id'];
                    $data['reward_uids'] = $v['reward_uids'];
                    $data['reward_percent'] = $v['reward_percent'];
                    $data['reward_bonus'] = $v['reward_bonus'];
                    $data['reward_uids_recommend'] = $v['reward_uids_recommend'];
                    $data['reward_percent_recommend'] = $v['reward_percent_recommend'];
                    $data['reward_bonus_recommend'] = $v['reward_bonus_recommend'];
                }
                $goodsExtends[] = $data;
            }
            M("OrderPackageItems")->addAll($goodsExtends);
        }
	}
	
	/**
	 * 订单交易成功后
	 * @param unknown $order 订单表一维数组
	 */
	protected function afterOrderCompleted( $order ) {
	    $order = $this->getOrder($order['id']);
	    $snapGoods = $order['snapGoods'];
	    /* 套餐类型 */
	    $packageType = DistributionShopPackageModel::PACKAGE_TYPE_UPDATE;
	    foreach ( $snapGoods as $id => $goods ) {
	        $packageType = $goods['type'];
	        break;
	    }
	    
	    if ( $packageType == DistributionShopPackageModel::PACKAGE_TYPE_UPDATE ) {
	        $upLevel = ''; // 升为代理等级
	        foreach ( $snapGoods as $id => $goods ) {
	            if ( $goods['config'] ) {
	                $pConfig = array();
	                if ( $goods['config']['base'] ) {
	                    $pConfig = $goods['config']['base'];
	                }
	                if ( $goods['config'][$goods['type']] ) {
	                    $pConfig = array_merge($pConfig, $goods['config'][$goods['type']] );
	                }
	                if ( isset($pConfig['toLevel']) ) {
	                    if ( $upLevel === '' or $upLevel === null ) {
	                        $upLevel = $pConfig['toLevel']*1;
	                    } else {
	                        $pConfig['toLevel']*1 <= $upLevel*1 and $upLevel = $pConfig['toLevel']*1;
	                    }
	                }
	            }
	        }
	        $userRole = new UserRole();
	        $type = $userRole->type($order['user_type']);
	        $agent = M("Agent")->where("cid=%d and wechat_uid=%d", $order['cid'], $order['uid'])->find(); // 查询当前买家是否的代理商
	        if ( !$agent ) { // 现在还不是代理
	            if ( $upLevel === '' or $upLevel === null ) {
	                // 订单中不包含升级套餐
	            } else { // 第一次购买代理商升级产品
	                $agentId = $order['agent_id']; // 代理推荐人id(从代理推荐人那儿进货)
	                /* 升级为代理 */
	                $data = array(
	                    'wechat_uid' => $order['uid'],
	                    'parent_id' => $agentId,
	                    'name' => '代理商',
	                    'cid' => $order['cid'],
	                    'email' => null,
	                    'password' => hash_pwd('111111'),
	                    'contacts' => $order['consignee'],
	                    'tel' => $order['tel'],
	                    'province' => $order['province'],
	                    'city' => $order['city'],
	                    'area' => $order['area'],
	                    'address' => $order['address'],
	                    'begin_time' => time(),
	                    'end_time' => strtotime("+1 year"),
	                    'is_role' => 0,
	                    'level' => $upLevel,
	                    'tree' => '', // 添加后更新
	                );
	                $id = M("Agent")->add($data);
	                if ( false !== $id ) {
	                    /* 添加代理商管理员 */
	                    $addData = array(
	                        'agent_id' => $id,
	                        'name' => $data['name'],
	                        'password' => $data['password'],
	                        'last_login_time' => 0,
	                        'last_login_ip' => '',
	                        'login_count' => 0,
	                        'is_role' => 0,
	                        'is_super' => 1,
	                    );
	                    $data['email'] and $addData['email'] = $data['email'];
	                    if ( $data['user_name'] ) {
	                        $addData['user_name'] = $data['user_name'];
	                    } else {
	                        $addData['user_name'] = "u".time().rand(10000, 99999);
	                    }
	                    M("AgentAdmin")->add( $addData );
	                    /* 对代理商的更新 */
	                    $writeData = array();
	                    /* 更新关系树 */
	                    $parentId = $data['parent_id']*1;
	                    if ( $parentId ) {
	                        $tree = M("Agent")->where('id=%d and cid=%d', $parentId, $data['cid'])->getField('tree');
	                        $tree = $id.','.$tree;
	                    } else {
	                        $tree = $id;
	                    }
	                    $writeData['tree'] = $tree;
	                    /* 更新父级 */
	                    $writeData['parent_id'] = $this->getNewParent($parentId, $upLevel);
	                    M("Agent")->where("id=%d", $id)->save($writeData);
	                }
	                /* 设置用户为代理商类型  */
	                $wechatUid = $data['wechat_uid'];
	                $m = M("WechatUser");
	                $wechatUser = $m->where("id=%d", $wechatUid)->find();
	                $userRole = new UserRole();
	                $type = $userRole->type($wechatUser['type'])->becomeTo(WechatUserModel::USER_TYPE_AGENT)->getType();
	                $m->where("id=%d", $wechatUid)->setField('type', $type);
	            }
	        } elseif( $userRole->isNot(WechatUserModel::USER_TYPE_AGENT) ) { // 当前是代理商,购买时不是代理
	            /* 代理升级 */
	            if ( $upLevel*1 < $agent['level']*1 ) {
	                $writeData = array(
	                    'level' => $upLevel,
	                );
	                // 寻找新的父级
	                $writeData['parent_id'] = $this->getNewParent($agent['parent_id'], $upLevel);
	                // 更新父级与级别
	                M("Agent")->where(array('id=%', $agent['id']))->save($writeData);
	            }
	        } else { // 已是代理商购买了升级产品
	            /* 代理升级 */
	            if ( $upLevel*1 < $agent['level']*1 ) {
	                $writeData = array(
	                    'level' => $upLevel,
	                );
	                // 寻找新的父级
	                $writeData['parent_id'] = $this->getNewParent($agent['parent_id'], $upLevel);
	                // 更新父级与级别
	                M("Agent")->where('id=%d', $agent['id'])->save($writeData);
	            }
	            $orderTotalBonus = array();
	            /* 层级返佣 */
	            if ( $order['reward_uids'] and $order['reward_bonus'] ) {
	                $layerBonus = array_combine(explode(',', $order['reward_uids']), explode(',', $order['reward_bonus']));
	                $layerBonus = array_filter($layerBonus, function($v) { if ( $v === '' ) { return false; } return true; });
	                foreach ( $layerBonus as $uid => $bonus ) {
	                    $orderTotalBonus[$uid] += $bonus;
	                }
	            }
	            /* 培养返佣 */
	            if ( $order['reward_uids_recommend'] and $order['reward_bonus_recommend'] ) {
	                $recommendBonus = array_combine(explode(',', $order['reward_uids_recommend']), explode(',', $order['reward_bonus_recommend']));
	                $recommendBonus = array_filter($recommendBonus, function($v) { if ( $v === '' ) { return false; } return true; });
	                foreach ( $recommendBonus as $uid => $bonus ) {
	                    $orderTotalBonus[$uid] += $bonus;
	                }
	            }
	            $settleOrder = array();
	            foreach ( $orderTotalBonus as $uid => $bonus ) {
	                $uid == 's' and $uid = 0;
	                $settleOrder[] = array(
	                    'cid' => $this->cid,
	                    'order_id' => $order['id'],
	                    'end_agent' => $uid,
	                    'bonus' => $bonus,
	                    'status' => 0,
	                );
	            }
	            $settleOrder and M("AgentOrderSettle")->addAll($settleOrder);
	        }
	    } elseif ( $packageType == DistributionShopPackageModel::PACKAGE_TYPE_STOCK ) {
	        /* 层级返佣 */
	        if ( $order['reward_uids'] and $order['reward_bonus'] ) {
	            $layerBonus = array_combine(explode(',', $order['reward_uids']), explode(',', $order['reward_bonus']));
	            $layerBonus = array_filter($layerBonus, function($v) { if ( $v === '' ) { return false; } return true; });
	            foreach ( $layerBonus as $uid => $bonus ) {
	                $orderTotalBonus[$uid] += $bonus;
	            }
	        }
	        /* 培养返佣 */
	        if ( $order['reward_uids_recommend'] and $order['reward_bonus_recommend'] ) {
	            $recommendBonus = array_combine(explode(',', $order['reward_uids_recommend']), explode(',', $order['reward_bonus_recommend']));
	            $recommendBonus = array_filter($recommendBonus, function($v) { if ( $v === '' ) { return false; } return true; });
	            foreach ( $recommendBonus as $uid => $bonus ) {
	                $orderTotalBonus[$uid] += $bonus;
	            }
	        }
	        $settleOrder = array();
	        foreach ( $orderTotalBonus as $uid => $bonus ) {
	            $uid == 's' and $uid = 0;
	            $settleOrder[] = array(
	                'cid' => $this->cid,
	                'order_id' => $order['id'],
	                'end_agent' => $uid,
	                'bonus' => $bonus,
	                'status' => 0,
	            );
	        }
	        $settleOrder and M("AgentOrderSettle")->addAll($settleOrder);
	    }
	}
	
	/**
	 * 获得新的父级id
	 * @param unknown $parentId
	 */
    private function getNewParent( $nowParentId, $newLevel) {
       /* 升为一级 */
       if ( $nowParentId ) {
           if ( $newLevel == 0 ) { // 有父级要升1级时
               return 0;
           } else {
               $parent = M("Agent")->where("cid=%d and id=%d", $this->cid, $nowParentId)->find();
               $parentLevel = $parent['level']*1;
               if ( $parentLevel >= $newLevel  ) { // 与当前父级同级或超越时
                   while( $parentLevel > 0 ) {
                       $parent = M("Agent")->where("cid=%d and id=%d", $this->cid, $parent['parent_id'])->find();
                       $parentLevel = $parent['level']*1;
                       if ( $parentLevel < $newLevel ) {
                           return $parent['id']*1;
                       }
                   }
                   return 0;
               } else {
                   return $nowParentId;
               }
           }
       }
       return 0;
    }
	
}